Color "Hex" Numbers

JavaScript colors are stored as 24-bit values that must be represented in base 16 (hexadecimal, or "hex" for short) before they can be used by JavaScript. Hex numbers range from zero to nine and the letter A through the letter F. In hexadecimal, the number 0x10 means 16. Here's a chart to compare values in hex (base 16) with decimal values (base 10).

Hex Numbers
HexDecimal HexDecimal HexDecimal HexDecimal
00 11 22 33
44 55 66 77
88 99 A10 B11
C12 D13 E14 F15


Try it out. Try converting your own numbers from decimal to hex and back. This utility uses the toHex() and toDecimal() functions to translate the data between hexadecimal and decimal formats. Try converting:
Decimal: :Hex


// --------------------Hexadecimal Conversion---------------------

// convert a single digit (0 - 16) into hex
function enHex(aDigit)
{
    return("0123456789ABCDEF".substring(aDigit, aDigit+1))
}

// convert a hex digit into decimal
function deHex(aDigit)
{
    return("0123456789ABCDEF".indexOf(aDigit))
}

// Convert a 24bit number to hex
function toHex(n)
{
    return (enHex((0xf00000 & n) >> 20) +
            enHex((0x0f0000 & n) >> 16) +
            enHex((0x00f000 & n) >> 12) +
            enHex((0x000f00 & n) >>  8) +
            enHex((0x0000f0 & n) >>  4) +
            enHex((0x00000f & n) >>  0))
}

// Convert a six character hex to decimal
function toDecimal(hexNum)
{
    var tmp = ""+hexNum.toUpperCase()
    while (tmp.length < 6) tmp = "0"+tmp
    
    return ((deHex(tmp.substring(0,1)) << 20) +
            (deHex(tmp.substring(1,2)) << 16) + 
            (deHex(tmp.substring(2,3)) << 12) +
            (deHex(tmp.substring(3,4)) << 8) +
            (deHex(tmp.substring(4,5)) << 4) +
            (deHex(tmp.substring(5,6))))
}
Copyright ©2000 by Charles River Media, All Rights Reserved